﻿using System.IO;
using Microsoft.SharePoint;

namespace RealDolmen.SharePoint.Helpers
{
    public class SPFileHelper
    {
        #region Publish / Approve
        public static void PublishAndApproveIfNecessary(SPFile file)
        {
            if (file.InDocumentLibrary)
            {
                file.Publish(string.Empty);
                if (file.Item.ModerationInformation != null)
                {
                    file.Approve(string.Empty);
                }
            }
        } 
        #endregion // Publish / Approve

        #region Check in / Check out
        public static void EnableForceCheckoutIfNecessary(SPFile file, SPWeb web)
        {
            if (file.InDocumentLibrary)
            {
                SPList list = web.Lists[file.ParentFolder.ParentListId];

                if (!list.ForceCheckout)
                {
                    list.ForceCheckout = true;
                    list.Update();
                }
            }
        }

        public static bool DisableForceCheckoutIfNecessary(SPFile file, SPWeb web)
        {
            if (file.InDocumentLibrary)
            {
                SPList list = web.Lists[file.ParentFolder.ParentListId];

                if (list.ForceCheckout)
                {
                    list.ForceCheckout = false;
                    list.Update();
                    return true;
                }
            }
            return false;
        } 
        #endregion // Check in / Check out

        #region I/O
        public static string ReadFile(string absoluteUrl)
        {
            string result = string.Empty;

            try
            {
                SPSite site = new SPSite(absoluteUrl);
                SPWeb web = site.OpenWeb();


                SPFile file = web.GetFile(absoluteUrl);
                StreamReader sr = new StreamReader(file.OpenBinaryStream());
                result = sr.ReadToEnd();

                SPHelper.TryDisposeWeb(web);
                SPHelper.TryDisposeSite(site);
            }
            catch { }
            return result;
        }
        public static byte[] ReadFileAsBinary(string absoluteUrl)
        {
            byte[] result = null;

            try
            {
                SPSite site = new SPSite(absoluteUrl);
                SPWeb web = site.OpenWeb();


                SPFile file = web.GetFile(absoluteUrl);
                result = file.OpenBinary();

                SPHelper.TryDisposeWeb(web);
                SPHelper.TryDisposeSite(site);
            }
            catch { }
            return result;
        }
        #endregion // IO
    }
}